#include "Task.hpp"
#include <vector>
#include <string>
#include <unistd.h>
#include <assert.h>
#include <time.h>
#include<sys/types.h>
#include <sys/wait.h>
int processnum=10;
std::vector<task_t> tasks;
class channel
{
    public:
    channel(int cmdfd,pid_t slaverid,const std::string &processname):_cmdfd(cmdfd),_slaverid(slaverid),_processname(processname)
    {}
    public:
    int _cmdfd;//文件描述符
    pid_t _slaverid ;//管道对应的进程
    std::string _processname;//子进程的名字
};
void slaver()
{
    while(true)
    {
        //读任务并执行
        //sleep(2);
        int cmdcode=0;//读取任务码到这个变量
        int n=read(0,&cmdcode,sizeof(int));
        //执行任务码
        if(n==sizeof(int))
        {
        if(cmdcode>=0&&cmdcode<tasks.size())
        tasks[cmdcode]();
        }
        if(n==0)break;
    }

}
void initchannels(std::vector<channel>* channels)
{
    for(int i=0;i<processnum;i++)
    {
        int pipefd[2];
        int retpipe=pipe(pipefd);
        assert(!retpipe);
        (void)retpipe;
        pid_t id=fork();
       if(id==0)
        {
            //child 读
            close(pipefd[1]);
            dup2(pipefd[0],0);//重定向管道的读到标准输入的读
            close(pipefd[0]);
            slaver();
            exit(0);
        }
        //farther
        close(pipefd[0]);//父写关读
        std::string processname="process"+std::to_string(i);
        channels->push_back(channel(pipefd[1],id,processname));

    }
}
void Debug(const std::vector<channel>&chan)
{
      //test
    for(auto &c:chan)
    {
        std::cout<<"fd: "<<c._cmdfd<<"slaverfd: "<<c._slaverid<<"processname: "<<c._processname<<std::endl;
    }
}
void Menu();
void ctrlSlaver(const std::vector<channel>&channels)
{
    int which=0;
    while(true)
    {
    Menu();
    int select=0;
    std::cout<<"请选择"<<std::endl;
    std::cin>>select;
    if(select>=5||select<=0)break;
    //①选择任务
   // int cmdcode=rand()%20;
    int cmdcode=select-1;

    //②选择进程  //随机方法
   // int process=rand()%channels.size();
    //③发送任务
    write(channels[which]._cmdfd,&cmdcode,sizeof(cmdcode));
    which++;
    which%=channels.size();
    }
}
void QuitProcess(const std::vector<channel>&channels)
{
    for(const auto& e:channels)
    {
        close(e._cmdfd);//关掉管道文件
    }
    for(const auto&e:channels)
    {
        waitpid(e._slaverid,NULL,0);//等待子进程
    }
}
void Menu()
{
    std::cout<<"#############################"<<std::endl;
    std::cout<<"#  1.刷新蓝buff  2.刷新红buff#"<<std::endl;
    std::cout<<"#  3.刷新技能    4.刷新地图  #"<<std::endl;
    std::cout<<"#############################"<<std::endl;
}
int main()
{
 
    locatask(&tasks);
     std::vector<channel> channels;//组织
     srand(time(nullptr)^1024^88);//种个时间种子
    //1.初始化
    initchannels(&channels);
   
    //2.控制子进程
    ctrlSlaver(channels);
    //3.清理数据
    QuitProcess(channels);
    return 0;
}